package com.university.logistic.exception;

import cn.hutool.json.JSONUtil;
import com.university.logistic.model.Result;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class ExceptionHandler implements ErrorWebExceptionHandler {
    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex){
        Result<?> result = Result.getResult().setMessage("出现异常").setCode(500);
        if(ex instanceof LogisticException){
            LogisticException exception=(LogisticException) ex;
            result.setCode(exception.getCode()).setMessage(exception.getMessage());
        }

        String data = JSONUtil.parse(result).toString();
        exchange.getResponse().getHeaders().setContentType(MediaType.APPLICATION_JSON);//设置响应参数格式为JSON
        return exchange.getResponse().writeWith(Mono.fromSupplier(()->{
            return exchange.getResponse().bufferFactory().wrap(data.getBytes());
        }));
    }
}
